<template>
  <div class="app-container">
    <page-search ref="searchRef" :search-config="searchConfig" @query-click="handleQueryClick"
      @reset-click="resetClick">
      <template #game_provider_id="scope">
        <el-select v-model="searchParam[scope.prop]" @change="setSearchParam()" v-bind="scope">
          <template v-for="option in supList" :key="option.id">
            <el-option :label="`${option.name}(${option.code})`" :value="option.id" />
          </template>
        </el-select>
      </template>
      <!-- setParams -->
      <template #category_id="scope">
        <el-select v-model="searchParam[scope.prop]" @change="setSearchParam()" v-bind="scope">
          <template v-for="option in gamesTypeList" :key="option.value">
            <el-option :label="option.name" :value="option.value" />
          </template>
        </el-select>
      </template>

    </page-search>
    <PageContent ref="contentRef" :gridOptions="gridOptions" :content-config="contentConfig" @addClick="addFn" @edit-click="handleEditClick"
      @export-click="handleExportClick" @toolbarClick="handleToolbarClick">


      <template #popular="scope">
        <el-tag :type="popularList[+scope.row[scope.prop]].type || ''">
          {{$t(popularList[+scope.row[scope.prop]].text) }}
        </el-tag>
      </template>
      <template #game_provider="scope">
        {{scope.row[scope.prop].name +`(${scope.row[scope.prop].code})`}}
      </template>

      <template #status="scope">
        <el-tag :type="statusList[scope.row[scope.prop]].type">
          {{ $t(statusList[scope.row[scope.prop]].text) }}
        </el-tag>
      </template>
      <template #categories="scope">
        <template v-for="item in scope.row.categories" :key="item.id">
          <el-tag class="mr-2">{{ item.name }}</el-tag>
        </template>
      </template>

    </PageContent>

    <!-- 新增 -->
    <page-modal ref="addModalRef" :modal-config="addModalConfig" @submit-click="handleSubmitClick">
      <template #game_provider_id="scope">
        <el-select v-model="param[scope.prop]" @change="changeAdd(param,'add')">
          <template v-for="option in supList" :key="option.id">
            <el-option :label="`${option.name}(${option.code})`" :value="option.id" />
          </template>
        </el-select>
      </template>
      <template #categories="scope">
        <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" v-model="param[scope.prop]"
          @change="changeAdd(param,'add')">
          <template v-for="option in gamesTypeList" :key="option.value">
            <el-option :label="option.name" :value="option.value" />
          </template>
        </el-select>
      </template>
      <template #meta="scope">
        <div v-for="(item, index) in param.meta" :key="index" class="w-full">
          <el-row :gutter="15" class="w-full mb-2">
            <el-col :span="10">
              <el-input :disabled="item.key ==='interval' && index ===0" v-model="item.key" :placeholder="t('hint.144')"  @change="changeAdd(param,'add')" />
            </el-col>
            <el-col :span="10">
              <el-input v-model="item.value" :placeholder="item.key ==='interval'?t('hint.146'):t('hint.145')"  @change="changeAdd(param,'add')" />
            </el-col>
            <el-col :span="4">
              <el-button v-if="index === 0" type="primary" class="block w-full" @click="addMeta">{{ t('btn.17') }}</el-button>
              <el-button v-if="param.meta.length > 1 && index !== 0" type="danger" class="block w-full" @click="removeMeta(index)">{{ t('btn.4') }}</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </page-modal>

    <!-- 编辑 -->
    <page-modal ref="editModalRef" :modal-config="editModalConfig" @submit-click="handleSubmitClick">
      <template #game_provider_id="scope">
        <el-select v-model="param[scope.prop]" @change="changeAdd(param,'edit')">
          <template v-for="option in supList" :key="option.id">
            <el-option :label="`${option.name}(${option.code})`" :value="option.id" />
          </template>
        </el-select>
      </template>
      <template #categories="scope">
        <el-select multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="3" v-model="param[scope.prop]"
          @change="changeAdd(param,'edit')">
          <template v-for="option in gamesTypeList" :key="option.value">
            <el-option :label="option.name" :value="option.value" />
          </template>
        </el-select>
      </template>
      <template #meta="scope">
        <div v-for="(item, index) in param.meta" :key="index" class="w-full">
          <el-row :gutter="15" class="w-full mb-2">
            <el-col :span="10">
              <el-input :disabled="item.key ==='interval' && index ===0 && param.categories.includes(2)" v-model="item.key"  :placeholder="t('hint.144')"  @change="changeAdd(param,'edit')" />
            </el-col>
            <el-col :span="10">
              <el-input v-model="item.value" :placeholder="item.key ==='interval'?t('hint.146'):t('hint.145')"  @change="changeAdd(param,'edit')" />
            </el-col>
            <el-col :span="4">
              <el-button v-if="index === 0" type="primary" class="block w-full" @click="addMeta">{{ t('btn.17') }}</el-button>
              <el-button v-if="param.meta.length > 1 && index !== 0" type="danger" class="block w-full" @click="removeMeta(index)">{{ t('btn.4') }}</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
    </page-modal>
  </div>
</template>

<script setup>
import searchConfig from "./config/search";
import contentConfig from "./config/content";
import addModalConfig from "./config/add";
import editModalConfig from "./config/edit";
import usePage from "@/hooks/usePage";
import Api from "@/api/thirdGames/supplier";
import typeApi from "@/api/thirdGames/categories"
import { tableHeightAutoAdjust } from '@/utils/common'
import { onMounted } from "vue";
// import { objToStr } from "@/utils/common";

defineOptions({
  name: "thirdGamesGame",
  inheritAttrs: false,
});

const { t } = useI18n();

const gridOptions = reactive({})

const { searchRef, contentRef, addModalRef, editModalRef,
  handleQueryClick, handleResetClick, handleAddClick,
  handleSubmitClick, handleExportClick, } = usePage();
const popularList = {
  0: { text: "status.2", type: "success" },
  1: { text: "status.1", type: "danger" },
}
const statusList = {
  0: { text: "status.21", type: "danger" },
  1: { text: "status.22", type: "success" },
  2: { text: "status.23", type: "primary" },
  3: { text: "status.24", type: "info" },
}
const param = ref({
  game_provider_id: '',
  categories: [],
  meta: [{key: '',value: '' }]
})
// 
const searchParam = ref({
  category_id:null
})
const isEdit = ref(null)
watch(
  () => [param.value.categories, isEdit.value], // 监听两个值的变化
  ([newCategories, newIsEdit], [oldCategories, oldIsEdit]) => {
    // 如果是新增
    if (!newIsEdit) {
      // 判断是不是彩票
      if (newCategories.length>0 && newCategories.includes(2)) {
        param.value.meta = [{ key: 'interval', value: '' }];
      } else {
        param.value.meta = [{ key: '', value: '' }];
      }
    }
    // 如果需要根据 isEdit 的变化做额外操作，可以在这里添加逻辑
    if (oldIsEdit !== newIsEdit) {
      console.log('isEdit 的值发生了变化');
      // 根据需要处理 isEdit 的变化逻辑
    }
  },
  { deep: true } // 如果需要深度监听，可以加上这个选项
);

const setSearchParam = () => {
  searchRef.value.setParams(searchParam.value)
}
const resetClick = () => {
  for (let i in searchParam.value) {
    searchParam.value[i] = ''
  }
  handleResetClick()
}
const handleEditClick = (row) => {
  console.log('回写数据====>?',row)
  isEdit.value = true
  for (let i in param.value) {
    if (i === 'categories') {
      param.value[i] = row['categories'].map((item)=>item.id)
    } else {
      param.value[i] = row[i]
      // 判断id是否等于2 即 彩票
      const hasIdTwo = row['categories'].some(item => item.id === 2)
      if(row['meta'].length === 0 ){
        if(hasIdTwo){
          param.value['meta'] = [{ key: 'interval', value: '' }]
        } else {
          param.value['meta'] = [{ key: '', value: '' }]
        }
      }
    }
  }
  // 模拟根据id获取数据进行填充
  editModalRef.value?.setModalVisible({...row,...param.value});
}
const changeAdd = (obj, type) => {
  if (type === 'edit') {
    editModalRef.value?.setModalVisible(obj);
  } else if (type === 'add') {
    addModalRef.value?.setModalVisible(obj);
  }
}
const supList = ref([])
const getSupList = async () => {
  const { data } = await Api.getList({ page: 1, per_page: 10 })
  supList.value = data
}
const addFn = () => {
  isEdit.value = false
  param.value.game_provider_id = ''
  param.value.categories = []
  param.value.meta = []
  handleAddClick()
}
const gamesTypeList = ref([])
const getGamesType = async () => {
  const { data } = await typeApi.getList({ page: 1, per_page: 100 })
  gamesTypeList.value = data.map((item)=>{
    return {
      name: item.name,
      value: item.id
    }
  })
  console.log('gamesTypeL===>',gamesTypeList.value)
}
const addMeta = () => {
  if (!param.value.meta) {
    param.value.meta = [{ key: 'interval', value: '' }];
  }
  param.value.meta.push({ key: '', value: '' });
};
const removeMeta = (index) => {
  if (param.value.meta && param.value.meta.length > index) {
    param.value.meta.splice(index, 1);
  }
};
onMounted(() => {
  getSupList()
  getGamesType()
  // 确保在组件挂载后立即设置高度
  tableHeightAutoAdjust(gridOptions);
})
</script>
